import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../API/goods/goods.dart';
import '../data/add_goods_data.dart';

class AddGoodsPage extends StatelessWidget {
  const AddGoodsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: false,
        title: const Text(
          '发闲置',
          style: TextStyle(
            color: Colors.black,
            fontSize: 20.0,
            fontWeight: FontWeight.bold,
          ),
        ),
        bottom: const PreferredSize(
          preferredSize: Size.fromHeight(1.0),
          child: Divider(color: Colors.black, thickness: 1.5),
        ),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 16.0),
            child: SizedBox(
              height: 30.0,
              child: ElevatedButton(
                onPressed: handlePublish,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(18.0),
                  ),
                ),
                child: const Text('发布', style: TextStyle(color: Colors.white)),
              ),
            ),
          ),
        ],
      ),
      body: const BuilderWidget(),
    );
  }
}

Future<void> handlePublish() async {
  final controller = Get.find<GoodsController>();

  if (controller.nameController.text.isEmpty) {
    showErrorDialog('请输入商品名称');
    return;
  }
  if (controller.priceController.text.isEmpty) {
    showErrorDialog('请输入商品价格');
    return;
  }
  if (!controller.campusSelected.value) {
    showErrorDialog('请选择校区');
    return;
  }
  if (controller.selectedTag.value == '') {
    showErrorDialog('请选择一个标签');
    return;
  }

  // 发布逻辑
  final response =await ItemApiService.addGoods(
    name: controller.nameController.text,
    price: double.parse(controller.priceController.text),
    description: controller.descriptionController.text,
    category: controller.selectedTag.value,
    campuses: [controller.selectedCampus.value],
  );
  if(response['code'] == 20011){
    // 先显示提示并延迟关闭页面
    Get.snackbar('提示', '发布成功', duration: Duration(seconds: 2));
    // 延迟2秒后关闭页面，确保用户能看到提示
    Future.delayed(Duration(seconds: 2), () {
      controller.clearForm();
      Get.back();
    });
  } else {
    // 补充错误提示
    Get.snackbar('错误', response['message'] ?? '发布失败');
    print(response);
  }
}

void showErrorDialog(String message) {
  Get.dialog(
    AlertDialog(
      title: const Text('提示'),
      content: Text(message),
      actions: [
        TextButton(onPressed: () => Get.back(), child: const Text('确定')),
      ],
    ),
  );
}

class BuilderWidget extends StatelessWidget {
  const BuilderWidget({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(GoodsController());

    return Container(
      color: Colors.white,
      child: ListView(
        padding: const EdgeInsets.all(25.0),
        children: [
          // 商品名称
          TextFormField(
            controller: controller.nameController,
            decoration: const InputDecoration(
              labelText: '商品名称',
              border: UnderlineInputBorder(),
            ),
          ),
          const SizedBox(height: 16.0),

          // 商品价格
          TextFormField(
            controller: controller.priceController,
            keyboardType: TextInputType.numberWithOptions(decimal: true),
            decoration: const InputDecoration(
              labelText: '商品价格',
              border: UnderlineInputBorder(),
              hintText: '0.00',
            ),
          ),

          const SizedBox(height: 16.0),

          // 商品描述
          TextFormField(
            controller: controller.descriptionController,
            maxLines: 5,
            decoration: const InputDecoration(
              labelText: '商品描述',
              border: OutlineInputBorder(),
            ),
          ),
          const SizedBox(height: 16.0),

          // 图片选择
          Obx(
            () => Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              children: [
                ...controller.selectedImages.asMap().entries.map((entry) {
                  final index = entry.key;
                  final file = entry.value;
                  return Stack(
                    children: [
                      Container(
                        width: 100,
                        height: 100,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: FileImage(File(file.path)),
                            fit: BoxFit.cover,
                          ),
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                      ),
                      Positioned(
                        right: 4,
                        top: 4,
                        child: GestureDetector(
                          onTap: () => controller.removeImage(index),
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.black54,
                              shape: BoxShape.circle,
                            ),
                            child: Icon(
                              Icons.close,
                              size: 20,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                }),
                // 添加图片按钮（带数量限制）
                if (controller.selectedImages.length<9)
                  GestureDetector(
                    onTap: () {
                      if (controller.selectedImages.length < 9) {
                        HapticFeedback.selectionClick();
                        controller.pickImage();
                      }
                    },
                    child: Container(
                      width: 100,
                      height: 100,
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                      child: const Icon(
                        Icons.panorama_outlined,
                        color: Colors.grey,
                      ),
                    ),
                  )
                else
                  const SizedBox.shrink(),
              ],
            ),
          ),

          const SizedBox(height: 24.0),

          // 校区选择
          const Text('选择校区：', style: TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(height: 8.0),
          CampusChoice(),
          const SizedBox(height: 24.0),

          // 标签选择
          const Text('添加标签：', style: TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(height: 8.0),
          TagChoice(),
        ],
      ),
    );
  }
}

class CampusChoice extends StatelessWidget {
  const CampusChoice({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<GoodsController>();

    return Wrap(
      spacing: 8.0,
      children: [
        Obx(
          () => ChoiceChip(
            checkmarkColor: Colors.white,
            selectedColor: Colors.blue,
            labelStyle: TextStyle(
              color:
                  controller.selectedCampus.value == '北洋园'
                      ? Colors.white
                      : Colors.black,
            ),
            label: const Text('北洋园'),
            selected: controller.selectedCampus.value == '北洋园',
            onSelected: (selected) {
              controller.selectedCampus.value = selected ? '北洋园' : '';
              controller.campusSelected.value = selected;
            },
          ),
        ),
        Obx(
          () => ChoiceChip(
            checkmarkColor: Colors.white,
            selectedColor: Colors.blue,
            labelStyle: TextStyle(
              color:
                  controller.selectedCampus.value == '卫津路'
                      ? Colors.white
                      : Colors.black,
            ),
            label: const Text('卫津路'),
            selected: controller.selectedCampus.value == '卫津路',
            onSelected: (selected) {
              controller.selectedCampus.value = selected ? '卫津路' : '';
              controller.campusSelected.value = selected;
            },
          ),
        ),
      ],
    );
  }
}

class TagChoice extends StatelessWidget {
  final List<String> tags = ['教材', '电子', '日用', '娱乐', '服饰', '二次元', '文具', '其他'];

  TagChoice({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<GoodsController>();

    return Wrap(
      spacing: 8.0,
      runSpacing: 8.0,
      children:
          tags
              .map(
                (tag) => Obx(
                  () => ChoiceChip(
                    showCheckmark: false,
                    checkmarkColor: Colors.white,
                    selectedColor: Colors.blue,
                    labelStyle: TextStyle(
                      color:
                          controller.selectedTag.value == tag
                              ? Colors.white
                              : Colors.black,
                    ),
                    label: Text(tag),
                    selected: controller.selectedTag.value == tag,
                    onSelected: (_) => controller.selectTag(tag),
                  ),
                ),
              )
              .toList(),
    );
  }
}
